﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BoYuan.MvcCodeGenerator.Controllers;
using BoYuan.MvcCodeTemplates;
using FineUIMvc;
using SqlSugar;

namespace BoYuan.MvcCodeGenerator.Areas.FineuiMvc.Controllers
{
    public class SetFineuiMvcCodeController : BaseController
    {
        // GET: FineuiMvc/SetFineuiMvcCode
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Btn_SetSimpleCode_OnClick(FormCollection fc)
        {
            var tables = fc["hd_tables"].Split(',');
            if (fc["hd_tables"].Length == 0 || tables.Length == 0)
            {
                NotifyError("获取表集合失败！");
                return UIHelper.Result();
            }

            try
            {
                foreach (string item in tables)
                {
                    SetCodeByTableName(item,fc);
                }
            }
            catch (Exception exception)
            {
                NotifyError(exception.Message);
                return UIHelper.Result();
            }

            NotifyInformation("生成简单代码成功!");
            return UIHelper.Result();
        }

        /// <summary>
        /// 生成页面代码，根据表
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        private void SetCodeByTableName(string tableName,FormCollection fc)
        {
            try
            {
                List<DbColumnInfo> cm = GetColumnDataByTableName(tableName);//字段信息集合

                string namespace2Str =fc["txb_Path"].Trim().Replace("/", ".");

                string savePath = fc["txb_savePath"].Trim();

                TableModel table = new TableModel();
                table.Columns = cm;
                table.ClassnameStr = fc["txb_BaseClassName"];
                table.NamespaceStr = fc["txb_NameSpace"];
                table.Namespace2Str = namespace2Str;
                table.ModelName = fc["txb_ModelName"];
                table.TableName = tableName;

                CreateFineuiMvcCode(savePath, table);
            }
            catch (Exception ex)
            {
                throw new Exception("生成代码有问题：表名称(" + tableName + ")" + ex.Message);
            }
        }
    }
}